/**
 * 分类服务
 * 提供分类相关的业务逻辑
 */
const { Category } = require('../models');
const { Op } = require('sequelize');
const CustomException = require('../utils/customException');
const ResultCodeEnum = require('../utils/resultCodeEnum');
const authConfig = require('../config/auth');
const jwt = require('jsonwebtoken');

class CategoryService {
  /**
   * 检查用户是否登录
   * @param {string} token - 用户token
   * @returns {Object} 用户信息
   * @throws {CustomException} 如果用户未登录
   */
  isLogin(token) {
    if (!token) {
      throw new CustomException(ResultCodeEnum.USER_NOT_LOGIN);
    }

    try {
      const decoded = jwt.verify(token, authConfig.jwt.secret);
      return {
        id: decoded.id
      };
    } catch (error) {
      if (error.name === 'TokenExpiredError') {
        throw new CustomException(ResultCodeEnum.TOKEN_EXPIRED_ERROR);
      } else {
        throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
      }
    }
  }

  /**
   * 获取分类列表
   * @param {string} token - 用户token
   * @returns {Promise<Array>} 分类列表
   * @throws {CustomException} 如果获取失败
   */
  async getCategories(token) {
    try {
      // 检查用户是否登录
      const user = this.isLogin(token);

      const categories = await Category.findAll({
        order: [
          ['id', 'ASC']
        ]
      });

      return categories;
    } catch (error) {
      if (error instanceof CustomException) {
        throw error;
      } else {
        console.error('获取分类列表异常:', error);
        throw new CustomException(ResultCodeEnum.SYSTEM_ERROR);
      }
    }
  }

  /**
   * 创建分类
   * @param {string} token - 用户token
   * @param {Object} categoryData - 分类数据
   * @returns {Promise<Object>} 创建的分类对象
   * @throws {CustomException} 如果创建失败
   */
  async createCategory(token, categoryData) {
    try {
      // 检查用户是否登录
      const user = this.isLogin(token);

      const category = await Category.create({
        name: categoryData.name,
        icon: categoryData.icon || '',
        bg_class: categoryData.bgClass || ''
      });

      return category;
    } catch (error) {
      if (error instanceof CustomException) {
        throw error;
      } else {
        console.error('创建分类异常:', error);
        throw new CustomException(ResultCodeEnum.PARAM_ERROR);
      }
    }
  }

  /**
   * 更新分类
   * @param {string} token - 用户token
   * @param {number} categoryId - 分类ID
   * @param {Object} categoryData - 分类数据
   * @returns {Promise<Object>} 更新的分类对象
   * @throws {CustomException} 如果分类不存在或更新失败
   */
  async updateCategory(token, categoryId, categoryData) {
    try {
      // 检查用户是否登录
      const user = this.isLogin(token);

      const category = await Category.findByPk(categoryId);

      if (!category) {
        throw new CustomException(ResultCodeEnum.CATEGORY_NOT_FOUND);
      }

      // 更新分类
      await category.update({
        name: categoryData.name,
        icon: categoryData.icon,
        bg_class: categoryData.bgClass
      });

      return category;
    } catch (error) {
      if (error instanceof CustomException) {
        throw error;
      } else {
        console.error('更新分类异常:', error);
        throw new CustomException(ResultCodeEnum.UPDATE_ERROR);
      }
    }
  }

  /**
   * 删除分类
   * @param {string} token - 用户token
   * @param {number} categoryId - 分类ID
   * @returns {Promise<boolean>} 是否删除成功
   * @throws {CustomException} 如果分类不存在或删除失败
   */
  async deleteCategory(token, categoryId) {
    try {
      // 检查用户是否登录
      const user = this.isLogin(token);

      const category = await Category.findByPk(categoryId);

      if (!category) {
        throw new CustomException(ResultCodeEnum.CATEGORY_NOT_FOUND);
      }

      // 删除分类
      await category.destroy();

      return true;
    } catch (error) {
      if (error instanceof CustomException) {
        throw error;
      } else {
        console.error('删除分类异常:', error);
        throw new CustomException(ResultCodeEnum.DELETE_ERROR);
      }
    }
  }
}

module.exports = new CategoryService();